package com.chenzp.rocketmq.contoller;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.TransactionSendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * @Classname ProducerController
 * @Description
 * @Version 1.0.0
 * @Date 2025-06-16 17:19
 * @Created by ncs
 */
@Slf4j
@RestController
@RequestMapping("producer")
public class ProducerController {

    @Autowired
    RocketMQTemplate rocketMQTemplate;

    @PostMapping("/send")
    public Map send(@RequestBody Message message){
        rocketMQTemplate.convertAndSend(message.getTopic(), message.getBody());
        HashMap<Object, Object> result = new HashMap<>();
        result.put("code", 0);
        return result;
    }

    @PostMapping("/sendTransaction")
    public Map sendTransaction(@RequestBody Message message){
        String topic = message.getTopic();
        String[] tags = new String[]{"tagA","tagB","tagC", "tagD", "tagE"};
        for (int i = 0; i < 10; i++) {
            org.springframework.messaging.Message<String> mqMessage = MessageBuilder.withPayload(message.getBody()).build();
            //topic和tag整合到了一起
            String destination = topic + ":" + tags[i % tags.length];
            //第三个参数是业务参数
            TransactionSendResult transactionSendResult = rocketMQTemplate.sendMessageInTransaction(destination, mqMessage, destination);
            log.info("事务消息发送结果{}", transactionSendResult);
        }
        HashMap<Object, Object> result = new HashMap<>();
        result.put("code", 0);
        return result;
    }
}
